import 'dart:developer';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stack_trace/stack_trace.dart';

clog(dynamic message, {String tag = "", bool always = false}) {
  if (kDebugMode) {
    var chain = Chain.current(); // Chain.forTrace(StackTrace.current);
    chain = chain.foldFrames((frame) => frame.isCore || frame.package == "flutter");
    final frames = chain.toTrace().frames;
    final idx = frames.indexWhere((element) => element.member == "clog");
    if (idx == -1 || idx + 1 >= frames.length) {
      return;
    }
    // 调用当前函数的函数信息帧
    final frame = frames[idx + 1];
    DateTime dateTime = DateTime.now();

    if (kDebugMode) {
      log("==🚩${tag.isNotEmpty ? "[$tag]" : ""} ${dateTime.toString()} $message - ${frame.uri.toString().split("/").last}(${frame.line})");
    } else {
      debugPrint("==🚩${tag.isNotEmpty ? "[$tag]" : ""} ${dateTime.toString()} $message - ${frame.uri.toString().split("/").last}(${frame.line})");
    }
  }
  logWrite(message, always: always || kDebugMode);
}

String logPath = '';

void logWrite(dynamic message, {bool always = false}) async {
  if (Platform.isAndroid && (kDebugMode || always)) {
    if (logPath.isEmpty) {
      final directory = await getExternalStorageDirectory();
      DateTime dateTime = DateTime.now();
      logPath = '${directory?.path}/one_video/${dateTime.year}-${dateTime.month}-${dateTime.day}/log.txt';
    }
    var logFile = File(logPath);
    if (!logFile.existsSync()) {
      await logFile.create(recursive: true);
    }
    var now = DateTime.now();
    final timestamp = "${now.year}-${now.month}-${now.day} ${now.hour} ${now.minute} ${now.second}";
    String msg = message.toString();
    msg = msg.length > 3000 ? (RegExp(r'[a-zA-Z]').hasMatch(msg) ? msg : msg.substring(0, 500)) : msg;
    final logEntry = '$timestamp: $msg\n';
    logFile.writeAsStringSync(logEntry, mode: FileMode.append);
  }
}
